//获取应用实例
const app = getApp();

Page({
  data: {
    goods_id: '', //商品ID
    addressList: [], //默认地址
    isDefaultAddress: false, //是否有默认地址
    num: 1,
    goodslist: [],
    minusStatus: 'disable',
    skuList: [{}],
  },
  onLoad: function(options) {
    this.setData({
      goods_id: options.goods_id,
      skuList: app.globalData.sku
    })

  },

  onShow: function() {
    this.getAddressList();
  },


  //获取收货地址列表
  getAddressList() {
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=ConsigneeAddress&a=getAddressList',
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      data: {
        'token': '' + app.globalData.token
      },
      success: (res) => {
        console.log(res)
        if (res.data.data.list.length > 0) {
          for (var i = 0; i < res.data.data.list.length; i++) {
            if (res.data.data.list[i].is_default == 'Y') {
              that.setData({
                addressList: res.data.data.list[i],
                isDefaultAddress: true
              })
            }
          }
        } else {
          that.setData({
            isDefaultAddress: false
          })
        }

        that.getGoodById(that.data.goods_id);
      },
    });
  },

  //选择收获地址
  chooseAddress() {
    wx.navigateTo({
      url: '../mine/setting-addresslist',
    })
  },

  failDiaolog: function() {
    wx.showToast({
      title: '请选择收货地址',
      icon: 'none'
    })
  },

  //获取商品详情
  getGoodById(id) {
    var that = this;
    wx.request({
      url: app.globalData.api + '/index.php/wap/Goods/getMsg',
      url: app.globalData.api + '/app.php?c=Tbk&a=getGoodsMsg',
      data: {
        num_iid: id,
        token: app.globalData.token
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        // for (var i = 0; i < 1; i++) {
        //   res.data.data.goodsMsg.img = app.globalData.imgUrl + "" + res.data.data.goodsMsg.img;
        //   that.setData({
        //     goodsMsg: res.data.data.goodsMsg,
        //     goods_id: res.data.data.goodsMsg.goods_id
        //   })
        // }
        that.setData({
          goodsMsg: res.data.data,
          goods_id: res.data.data.num_iid
        })
        
        // that.count_price();

      },
      fail: function() {

      }
    });
  },

  //事件处理函数
  /*点击减号*/
  bindMinus: function() {
    var num = this.data.num;
    if (num > 1) {
      num--;
    }
    var minusStatus = num > 1 ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus
    })
    // 调用计算金额方法
    this.count_price();
  },
  /*点击加号*/
  bindPlus: function() {
    var num = this.data.num;
    num++;
    var minusStatus = num > 1 ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus
    })
    // 调用计算金额方法
    this.count_price();
  },
  /*输入框事件*/
  bindManual: function(e) {
    var num = e.detail.value;
    var minusStatus = num > 1 ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus
    })
  },

  /**
   * 计算总价
   */
  count_price() {
    var that = this;
    let total = 0;
    // 所有价格加起来 count_money
    total += that.data.num * that.data.goodsMsg.price;
    // 最后赋值到data中渲染到页面
    this.setData({
      totalPrice: total.toFixed(2)
    });
  },

  //提交订单
  submitOrder() {
    var that = this;
    // console.log(that.data.skuList)
    wx.request({
      url: app.globalData.api + '/index.php/wap/Order/order',
      data: {
        token: app.globalData.token,
        goods_id: that.data.goods_id,
        // goods_sku:"["+that.data.skuList+"]",
        num: that.data.num,
        address_id: '' + that.data.addressList.id,
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function(res) {
        // console.log(res);
        if (res.data.code == 1) {
          that.getPayForm(res.data.data.order_id);
          // wx.switchTab({
          //   url: '/pages/mine/mine',
          // })

          // wx.navigateTo({
          //   url: 'order?goods_id=' + that.data.goods_id,
          // })
        } else {
          wx.showToast({
            title: '' + res.data.msg,
            icon: 'none',
            duration: 1000
          })
        }

      },
      fail: function() {

      }
    });
  },


  //获取支付表单
  getPayForm(order_id) {
    var that = this;
    console.log(order_id)
    console.log(app.globalData.payfrom)
    console.log(app.globalData.openid)
    wx.request({
      url: app.globalData.api + '/index.php/wap/Order/getPayForm',
      data: {
        token: app.globalData.token,
        order_id: order_id,
        pay_method: '' + app.globalData.payfrom,
        open_id: app.globalData.openid
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function(res) {
        console.log(res);
        if (res.data.code == 1) {
          wx.showToast({
            title: '购买成功',
            icon: 'success',
            duration: 2000
          })

          setTimeout(function() {
            //要延时执行的代码
            wx.navigateBack({
              delta: 1
            })
          }, 2000) //延迟时间 这里是1秒

          // "{"appid":"wx48126316bdbec25b","noncestr":"lk8qhri54a7stxryu88e4n5tuhgc0f7f","package":"Sign = WXPay","partnerid":"1498191702","prepayid":"wx23131631764983da394a941c1058073000","sign_type":"HMAC - SHA256","timestamp":1590210991,"sign":"F9B89B33AC715AABE0C69AC825E1104BA283335731A01C1C7200C13420E65FFF"}"

          // var tempJson = JSON.parse(res.data.data.pay_parameters)
          // console.log(tempJson)
          // console.log(tempJson.appid)
          // var packages = "prepay_id=" + tempJson.prepayid
          // console.log(packages)
          // wx.requestPayment(
          //   {
          //     'timeStamp': '' + tempJson.timestamp,
          //     'nonceStr': '' + tempJson.noncestr,
          //     'package': "" + packages,
          //     'signType': 'MD5',
          //     'paySign': '' + tempJson.sign,
          //     'success': function (res) {
          //       console.log(res)
          //       wx.showToast({
          //         title: '购买成功',
          //         icon: 'success',
          //         duration: 2000
          //       })

          //       setTimeout(function () {
          //         //要延时执行的代码
          //         wx.navigateBack({
          //           delta: 1
          //         })
          //       }, 2000) //延迟时间 这里是1秒
          //     },
          //     'fail': function (res) {
          //       console.log(res)
          //     },
          //     'complete': function (res) {
          //       console.log(res)
          //     }
          //   })
        } else {
          wx.showToast({
            title: '' + res.data.msg,
            icon: 'none',
            duration: 1000
          })
        }


      },
      fail: function() {

      },
      complete() {

      }
    });
  },

  //更换支付人
  changePay: function() {
    wx.navigateTo({
      url: 'pay-add',
    })
  }

});